/*
 * @(#)FileTablesConfig.java   1.0  2021年11月9日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.dts.loadconfig;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.swift.dts.loadconfig.model.TablesConfig;
import com.swift.exception.extend.SystemException;
import com.swift.util.exec.PathUtil;
import com.swift.util.type.JsonUtil;
import com.swift.util.type.TypeUtil;

/**
 * 添加说明
 * 
 * @author zhengjiajin
 * @version 1.0 2021年11月9日
 */
@Component
public class FileTablesConfig extends AbstractDtsConfigInterface<TablesConfig> {

    private static final String tables_file = "/data/config/tables.json";
    /**
     * @see com.swift.core.env.AbstractConfigInterface#loadFile()
     */
    @Override
    public List<TablesConfig> loadNew() {
        Map<?, ?> map = loadMap();
        if (TypeUtil.isNull(map)) return null;
        List<TablesConfig> list = new ArrayList<>();
        for (Object key : map.keySet()) {
            TablesConfig config = new TablesConfig();
            config.setKey(TypeUtil.toString(key));
            config.setRegex(map.get(key));
            list.add(config);
        }
        return list;
    }

    /** 
     * @see com.swift.dts.loadconfig.AbstractDtsConfigInterface#getFilePath()
     */
    @Override
    public String getFilePath() {
        return tables_file;
    }
    
    @Override
    public void saveConfig(List<TablesConfig> listT) {
        if(listT==null) return;
        try {
            Map<String, Object> map = listToMap(listT);
            String json = JsonUtil.toJson(map);
            BufferedWriter out = new BufferedWriter(new FileWriter(PathUtil.findOnClassPath(getFilePath())));
            out.write(json);
            out.close();
        } catch (IOException e) {
            throw new SystemException("写"+PathUtil.findOnClassPath(getFilePath())+"文件失败",e);
        }
    }
    
    public Map<String, Object> listToMap(List<TablesConfig> listT) {
        Map<String, Object> map = new HashMap<>();
        if(TypeUtil.isNull(listT)) return map;
        for(TablesConfig config:listT) {
            map.put(config.getKey(), config.getRegex());
        }
        return map;
    }
    
    public Map<?, ?> loadMap(){
        Map<?, ?> map = JsonUtil.toObj(loadFile(), Map.class);
        return map;
    }
    
    public void saveMap(Map<?, ?> map) {
        try {
            String json = JsonUtil.toJson(map);
            BufferedWriter out = new BufferedWriter(new FileWriter(PathUtil.findOnClassPath(getFilePath())));
            out.write(json);
            out.close();
        } catch (IOException e) {
            throw new SystemException("写"+PathUtil.findOnClassPath(getFilePath())+"文件失败",e);
        }
    }

}
